﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Primitive.Mvvm.Framework.Interfaces;
using UIController.ViewModels;

namespace UIController.Views
{
    public partial class LeftTreeView : UserControl, IWindowContainer
    {
        private LeftTreeViewModel _model;
        public LeftTreeView()
        {
            InitializeComponent();
        }

        public bool Initialize(IModel model, IMediator mediator, List<Exception> exceptions)
        {
            _model = new LeftTreeViewModel(model, mediator);
            _model.RefreshViewFunc = OnRefreshView;

            var res = Refresh(exceptions);
            if(res && treeView.Nodes.Count > 0)
                SelectDrawer(treeView.Nodes[0]);

            return res;
        }

        public void Clear(out Exception exception)
        {
            exception = null;
            try
            {
                treeView.Nodes.Clear();
                _model = null;
            }
            catch (Exception ex)
            {
                exception = ex;
            }
        }

        private bool OnRefreshView(IViewCallback o)
        {
            bool res = false;
            if(_model.CanRefreshView(o))
            {
                var listExc = new List<Exception>();
                res = Refresh(listExc);
                if (listExc.Count > 0)
                {
                    var ecx = new AggregateException("Refresh exception in BottomView", listExc);
                    throw ecx;
                }
            }

            return res;
        }

        private bool Refresh(List<Exception> exceptions)
        {
            try
            {
                var tree = _model.GetTreeElements();

                foreach (var treeNode in tree)
                {
                    if (treeNode != null)
                        treeView.Nodes.Add(treeNode);
                }
                
                return true;
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }

            return false;
        }

        void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            SelectDrawer(e.Node);
        }

        private void SelectDrawer(TreeNode node)
        {
            var selected = node ?? treeView.SelectedNode;
            if (selected != null)
            {
                var command = _model.SelectCategoryCommand;
                var obj = new CategoryHolder {Current = selected.Tag};
                if (command.CanExecute(obj))
                    command.Execute(obj);
            }
        }
    }
}
